package framework.util;

import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
import org.apache.commons.lang3.StringUtils;
import org.krysalis.barcode4j.impl.code39.Code39Bean;
import org.krysalis.barcode4j.output.bitmap.BitmapCanvasProvider;
import org.krysalis.barcode4j.tools.UnitConv;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;

/**
 * 条形码工具类（一维码） <br/>
 * 生成条形码用barcode4j比较好，因为zxing只支持EAN8和EAN13这两种格式的条形码，而barcode4j是全部都支持的，参考博客：https://www.cnblogs.com/littleatp/p/4815921.html <br/>
 * 解析条形码只能用zxing，因为barcode好像没有相关API <br/>
 *
 * @author 吴宇亮 on 2019/9/13 10:41
 */
public class _BarcodeUtil {

    /*public static void main(String[] args) throws FileNotFoundException {
        String msg = "123456789";
        String path = "F:/barcode.png";
        generateFile(msg, path);
    }*/

    /**
     * 将条形码的信息放到图片中，并把图片生成在path下
     *
     * @param msg 条形码的信息
     * @param path 生成文件的路径
     */
    public static File encoding(String msg, String path) throws FileNotFoundException {
        File file = new File(path);
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        generate(msg, fileOutputStream);
        return file;
    }

    /**
     *
     * @param msg
     * @param response
     * @throws IOException
     */
    public static void encoding(String msg, HttpServletResponse response) throws IOException {
        ServletOutputStream outputStream = response.getOutputStream();
        generate(msg, outputStream);
    }

    /**
     * 接收一个OutputStream，将生成完的图片放到OutputStream里
     */
    public static void generate(String msg, OutputStream ous) {
        if (StringUtils.isEmpty(msg) || ous == null) {
            return;
        }
        Code39Bean bean = new Code39Bean();
        // 精细度
        final int dpi = 150;
        // module宽度
        final double moduleWidth = UnitConv.in2mm(1.0f / dpi);
        // 配置对象
        bean.setModuleWidth(moduleWidth);
        bean.setWideFactor(3);
        bean.doQuietZone(false);

        String format = "image/png";
        try {
            // 输出到流
            BitmapCanvasProvider canvas = new BitmapCanvasProvider(ous, format, dpi, BufferedImage.TYPE_BYTE_BINARY, false, 0);
            // 生成条形码
            bean.generateBarcode(canvas, msg);
            // 结束绘制
            canvas.finish();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static String decode(InputStream inputStream) {
        try {
            //将inputstream -》 内存中的一张图片
            BufferedImage image = ImageIO.read(inputStream);
            LuminanceSource source = new BufferedImageLuminanceSource(image);
            BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));

            Result result = new MultiFormatReader().decode(bitmap, null);
            return result.getText();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
